package com.zareal.ymcc.mq.listener;


import com.alibaba.fastjson.JSON;
import com.zareal.ymcc.domain.PayOrder;
import com.zareal.ymcc.dto.PayExtParamsDto;
import com.zareal.ymcc.dto.PayNotifyLocalTxParamDto;
import com.zareal.ymcc.service.IPayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @description:
 * @author: Bug修复机
 * @date: 2022年10月17日 ： 10:49
 * @version: ver1.0
 * @email tangli@itsource.cn
 */
@Component
@Slf4j
@RocketMQTransactionListener(txProducerGroup = "tx-pay-notify-group")
public class PayNotifyTxListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IPayOrderService payOrderService;

    /**
     * 执行本地事务方法
     * @param message
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        try {
            log.info("课程异步通知处理本地事务开始！");
            if (arg == null){
                return RocketMQLocalTransactionState.ROLLBACK; // 不消费消息
            }
            PayNotifyLocalTxParamDto payNotifyLocalTxParamDto = JSON.parseObject(arg.toString(), PayNotifyLocalTxParamDto.class);
            payOrderService.asyncNotifyHandler(payNotifyLocalTxParamDto);
            log.info("课程异步通知处理本地事务结束！");
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("课程异步通知处理本地事务异常");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }


    /**
     * 检查本地事务方法
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 1.将数据转换为字节数组
        try {
            byte[] bytes = (byte[]) message.getPayload();
            // 2.转换为我们想要的对象
            String paramStr = new String(bytes, StandardCharsets.UTF_8);
            PayExtParamsDto payExtParamsDto = JSON.parseObject(paramStr, PayExtParamsDto.class);
            if (payExtParamsDto == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            PayOrder payOrder = payOrderService.selectByOrderNo(payExtParamsDto.getOrderNo());
            if (payOrder == null || (!payOrder.getPayStatus().equals(PayOrder.SUCCESS_PAY_STATUS))){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
